package com.ds.robot.assistant.service.impl;

import com.ds.robot.assistant.model.ApiResponse;
import com.ds.robot.assistant.service.HolidayService;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.RestTemplate;

import java.util.Optional;

/**
 * 作用：
 * 类型 0 工作日（包括假期前后的补班）
 * 1 假日（其实就是休息日）
 * 2 节假日 如果ignoreHoliday参数为true，这个字段不返回
 *
 * @author WeiShaoying
 * 
 */
@Service("holidayRollService")
@Slf4j
@NoArgsConstructor
public class HolidayRollServiceImpl implements HolidayService {

    @Autowired
    private RestTemplate restTemplate;

    @Value("${holiday.service.appId}")
    private String appId;

    @Value("${holiday.service.appSecret}")
    private String appSecret;


    /**
     * 获取指定日期的假期信息
     *
     * @param date 日期（格式：yyyyMMdd）
     * @return ApiResponse 对象
     */
    public ApiResponse getHoliday(String date) {
        String url = String.format("https://www.mxnzp.com/api/holiday/single/%s?ignoreHoliday=false&app_id=%s&app_secret=%s", date, appId, appSecret);
        log.debug("假期API：{}", url);
        HttpHeaders headers = new HttpHeaders();
        // headers.add("Accept", "application/json");
        HttpEntity<String> entity = new HttpEntity<>(headers);
        try {
            ResponseEntity<ApiResponse> response = restTemplate.exchange(
                    url,
                    HttpMethod.GET,
                    entity,
                    ApiResponse.class
            );
            if (response.getStatusCode().is2xxSuccessful()) {
                return response.getBody();
            } else {
                log.error("Unexpected HTTP status: {}", response.getStatusCode());
                throw new RuntimeException("Unexpected HTTP status: " + response.getStatusCode());
            }
        } catch (HttpClientErrorException | HttpServerErrorException e) {
            log.error("HTTP error occurred while calling the API: {}", e.getMessage(), e);
            throw new RuntimeException("HTTP error occurred: " + e.getMessage(), e);
        } catch (Exception e) {
            log.error("An unexpected error occurred while calling the API: {}", e.getMessage(), e);
            throw new RuntimeException("An unexpected error occurred: " + e.getMessage(), e);
        }
    }

    @Override
    public boolean isWorkDay(String date) {
        date = date.replaceAll("-", "");
        ApiResponse holiday = getHoliday(date);
        return Optional.ofNullable(holiday).map(ApiResponse::getData).map(ApiResponse.Data::getType).orElse(-1) == 0;
    }

    @Override
    public boolean isRestDay(String date) {
        return !isWorkDay(date);
    }

    @Override
    public boolean isHoliday(String date) {
        date = date.replaceAll("-", "");
        ApiResponse holiday = getHoliday(date);
        int type = Optional.ofNullable(holiday).map(ApiResponse::getData).map(ApiResponse.Data::getType).orElse(-1);
        return type == 2;
    }

}
